<template>
  <el-menu-item @click="handleUserManage" index="13">用户管理</el-menu-item>
  <div v-show="showUserManage" class="overlay"></div>
  <div class="userManage" v-show="showUserManage">
    <div class="manageTitle">
      <h4>用户管理</h4>
      <div class="close" @click="handleCloseBox">×</div>
    </div>
    <div class="manageNav">
      <div class="navAdd" @click="handleUserAdd">➕ 新增</div>
      <div class="navEdit">
        <input
          type="text"
          placeholder="搜索用户"
          v-model="searchUsername"
          @input="handleSearchUser"
        />
        <div class="icon-container">
          <i class="iconfont icon-zhongzhi" @click="refreshPage"></i>
        </div>
        <div class="icon-container">
          <i class="iconfont icon-biaogedaochu" @click="exportTableToExcel"></i>
        </div>
      </div>
    </div>
    <div class="manageUserList">
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>用户名</th>
            <th>用户类型</th>
            <th>登录状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in currentUsersList" :key="item.id">
            <td>{{ index + 1 + (currentPage - 1) * 8 }}</td>
            <td><span v-html="item.username"></span></td>
            <td>
              {{
                item.type === 'admin'
                  ? '管理员'
                  : `${item.type === 'common' ? '普通用户' : '交通部门'}`
              }}
            </td>
            <td>
              {{
                item.type === 'admin'
                  ? '正在登录'
                  : `${item.isOnline ? '在线中...' : '离线'}`
              }}
            </td>
            <td v-if="item.type !== 'admin'">
              <button
                class="edit"
                @click="handleUserEdit(index + (currentPage - 1) * 8)"
              >
                修改
              </button>
              <button
                class="delete"
                @click="handleDeleteUser(index + (currentPage - 1) * 8)"
              >
                注销
              </button>
              <button
                v-if="item.isOnline"
                class="offline"
                @click="handleOfflineUser(index + (currentPage - 1) * 8)"
              >
                下线
              </button>
            </td>
          </tr>
        </tbody>
        <tfoot>
          <tr v-if="currentUsersList.length === 0" style="color: #666666">
            <td colspan="5">未找到符合条件的用户</td>
          </tr>
        </tfoot>
      </table>
    </div>
    <el-pagination
      size="small"
      layout="prev, pager, next"
      :page-size="8"
      :total="allUserList.length"
      @current-change="currentPageChange"
    />
  </div>
  <div class="userAdd" v-show="showUserAdd">
    <div class="addUserTitle">
      <h4>新增交通部门用户</h4>
      <div class="close" @click="handleCloseAddBox">×</div>
    </div>
    <div class="addForm">
      <div class="formItem1">
        用户名
        <input
          type="text"
          v-model="addusername"
          placeholder="请输入账号(不能为空)"
        />
      </div>
      <div class="addErrorTip" v-show="addNamError">
        该用户已被注册！请更换账号
      </div>
      <div class="formItem2">
        密码
        <input
          type="password"
          v-model="addpassword"
          placeholder="请输入密码(最多不超过10位)"
        />
      </div>
      <div class="addErrorTip" v-show="addPasError">账号或密码输入有误</div>
    </div>
    <div class="addBtn">
      <button class="addA" @click="handleAddUser">新增</button>
      <button class="cancelA" @click="handleCloseAddBox">取消</button>
    </div>
  </div>
  <div class="userEdit" v-show="showUserEdit">
    <div class="editUserTitle">
      <h4>修改用户</h4>
      <div class="close" @click="handleCloseEditBox">×</div>
    </div>
    <div class="editForm">
      <div class="formItem1">
        用户名
        <input
          type="text"
          v-model="editusername"
          placeholder="请输入账号(不能为空)"
        />
      </div>
      <div class="editErrorTip" v-show="editNamError">
        该用户已被注册！请更换账号
      </div>
      <div class="formItem2">
        密码
        <input
          type="password"
          v-model="editpassword"
          placeholder="请输入密码(最多不超过10位)"
        />
      </div>
      <div class="editErrorTip" v-show="editPasError">账号或密码输入有误</div>
    </div>
    <div class="editBtn">
      <button class="editE" @click="handleEditUser">修改</button>
      <button class="cancelE" @click="handleCloseEditBox">取消</button>
    </div>
  </div>
</template>

<script setup>
import * as XLSX from 'xlsx'
import { ref, onMounted, computed } from 'vue'
import {
  getRegisterHttp,
  getLogoutHttp,
  getDeleteUserHttp,
  getUpdateUserHttp,
  getUsersHttp,
} from '@/api/request/index.js'

/* ----------------------------定义变量----------------------------< */
/* ----------超管 用户管理 界面---------- */
/* 控制用户管理组件 显隐 */
const showUserManage = ref(false)
/* 获取 所有用户信息 */
const allUserList = ref([])
/* 获取 交管部门用户信息 */
const trafficUserList = ref([])
/* 存取 当前页码 */
const currentPage = ref(1)
/* 存取 搜索用户名 */
const searchUsername = ref('')

/* ----------新增 用户管理 弹框---------- */
/* 控制 用户新增组件 显隐 */
const showUserAdd = ref(false)
/* 存取 新增用户名和密码 */
const addusername = ref('')
const addpassword = ref('')
/* 定义 新增注册错误提示 */
const addNamError = ref(false)
const addPasError = ref(false)

/* ----------修改 用户管理 弹框---------- */
/* 控制 用户修改组件 显隐 */
const showUserEdit = ref(false)
/* 存取 修改用户的对象 */
const editUser = ref({})
/* 存取 修改用户名和密码 */
const editusername = ref('')
const editpassword = ref('')
/* 定义 修改注册错误提示 */
const editNamError = ref(false)
const editPasError = ref(false)

/* ----------------------------<超管>弹窗主界面 弹框显隐存储、数据获取、分页、列表渲染、界面刷新、表格导出------------------------------*/
/* 事件处理 超管界面 用户管理弹框函数 */
let manageBox = localStorage.getItem('manageBox')
if (manageBox) {
  showUserManage.value = JSON.parse(manageBox)
}
const handleUserManage = () => {
  showUserManage.value = !showUserManage.value
  if (showUserManage.value) {
    localStorage.setItem('manageBox', JSON.stringify(showUserManage.value))
  }
}
/* 事件处理 关闭用户管理函数 */
const handleCloseBox = () => {
  showUserManage.value = false
  localStorage.removeItem('manageBox')
}
/* 监听current-change 当前页码改变函数 */
const currentPageChange = (page) => {
  currentPage.value = page
}
/* 计算 每页不同用户信息存储数组 */
const currentUsersList = computed(() => {
  // 获取当前页码固定数量的用户信息
  let start = (currentPage.value - 1) * 8
  let end = start + 8
  return allUserList.value.slice(start, end)
})
/* 事件处理 超管用户列表 界面刷新 */
const refreshPage = () => {
  location.reload()
  allUserList.value = JSON.parse(localStorage.getItem('allUserList'))
  searchUsername.value = ''
}
/* 事件处理 超管用户列表 导出表格 */
const exportTableToExcel = () => {
  // 获取表格数据
  const ws = XLSX.utils.table_to_sheet(
    document.querySelector('.userManage table')
  )
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 导出为 Excel 文件
  XLSX.writeFile(wb, 'table_data.xlsx')
}

/* ----------------------------<超管>搜索、增、删、改、查------------------------------*/
/* ----------超管搜索！ 搜索用户、字体颜色渲染！---------- */
/* 事件处理 搜索用户函数 */
const handleSearchUser = () => {
  allUserList.value = JSON.parse(localStorage.getItem('allUserList'))
  let searchList = allUserList.value.filter((item) =>
    item.username.includes(searchUsername.value)
  )
  allUserList.value = searchList.map((item) => {
    return {
      ...item,
      username: item.username.replace(
        searchUsername.value,
        `<span style="color: #409eff;">${searchUsername.value}</span>`
      ),
    }
  })
}

/* ----------超管新增！ 交通部门用户弹框、数据、存储！---------- */
/* 存储关闭用户 新增函数 */
let addBox = localStorage.getItem('addBox')
if (addBox) {
  showUserAdd.value = JSON.parse(addBox)
}
/* 事件处理 存储新增 用户的显隐 */
const handleUserAdd = () => {
  showUserAdd.value = true
  localStorage.setItem('addBox', JSON.stringify(showUserAdd.value))
}
const handleCloseAddBox = () => {
  showUserAdd.value = false
  localStorage.removeItem('addBox')
}
/* 事件处理 新增用户函数 */
const handleAddUser = async () => {
  // 校验账号是否已被注册
  if (
    trafficUserList.value.some((item) => item.username === addusername.value) &&
    addpassword.value !== ''
  ) {
    addNamError.value = true
    addPasError.value = false
    addpassword.value = ''
  } else if (
    addusername.value.trim() === '' ||
    addpassword.value === '' ||
    addpassword.value.length > 10
  ) {
    addNamError.value = false
    addPasError.value = true
    return
  } else {
    // 请求注册接口
    const res = await getRegisterHttp({
      username: addusername.value.trim(),
      password: addpassword.value,
      type: 'traffic',
    })
    console.log(res) // 打印 注册接口返回结果
    addNamError.value = false
    addPasError.value = false
    alert('新增用户成功')
    addusername.value = ''
    addpassword.value = ''
    // 注册成功，返回
    handleCloseAddBox()
  }
}

/* ----------button删除 用户提示、数据、列表渲染---------- */
/* 事件处理 注销用户函数 */
const handleDeleteUser = async (index) => {
  const deleteUser = allUserList.value[index]
  const result = confirm(
    `注销后，该用户将无法登录系统！确定要注销<${
      deleteUser.type === 'admin'
        ? '管理员'
        : `${deleteUser.type === 'common' ? '普通用户' : '交通部门'}`
    }>: '${deleteUser.username}' 的用户账号吗？`
  )
  if (result) {
    const res = await getDeleteUserHttp(deleteUser)
    console.log(res) // 打印 注销的用户信息
    if (res.status === 200) {
      allUserList.value.splice(index, 1) // 从 users 列表中删除该用户
      alert('注销成功！')
    } else {
      alert('注销失败！')
    }
  }
}

/* ----------button修改！ 用户弹框、数据、存储！---------- */
/* 存储关闭用户 修改函数 */
let editBox = localStorage.getItem('editBox')
let edituser = localStorage.getItem('editUser')
if (editBox && edituser) {
  showUserEdit.value = JSON.parse(editBox)
  let editUserData = JSON.parse(edituser)
  console.log(editUserData)
  editusername.value = editUserData.username
  editpassword.value = editUserData.password
}
/* 事件处理 存储修改 用户的显隐 */
const handleUserEdit = async (index) => {
  showUserEdit.value = true
  editUser.value = allUserList.value[index]
  editusername.value = editUser.value.username
  editpassword.value = editUser.value.password
  localStorage.setItem('editUser', JSON.stringify(editUser.value))
  localStorage.setItem('editBox', JSON.stringify(showUserEdit.value))
}
const handleCloseEditBox = () => {
  showUserEdit.value = false
  localStorage.removeItem('editBox')
  localStorage.removeItem('editUser')
}
/* 事件处理 修改用户函数 */
const handleEditUser = async () => {
  editUser.value = JSON.parse(localStorage.getItem('editUser'))
  console.log(editUser.value) // 打印 本地存储的要修改的用户信息
  const typeRes = await getUsersHttp({
    type: editUser.value.type,
  })
  let typeUsers = typeRes.data.result
  // console.log('更改此类的所有用户', typeUsers)
  let editUsers = typeUsers.filter((item) => item.id !== editUser.value.id)
  console.log('除更改项之外的此类所有用户', editUsers)
  if (
    editUsers.some((item) => item.username === editusername.value) &&
    editpassword.value !== ''
  ) {
    editNamError.value = true
    editPasError.value = false
    editpassword.value = ''
  } else if (
    editusername.value.trim() === '' ||
    editpassword.value === '' ||
    editpassword.value.length > 10
  ) {
    editNamError.value = false
    editPasError.value = true
    return
  } else {
    // 请求注册接口
    const res = await getUpdateUserHttp({
      id: editUser.value.id,
      username: editusername.value,
      password: editpassword.value,
      type: editUser.value.type,
      isOnline: editUser.value.isOnline,
    })
    console.log(res) // 打印 注册接口返回结果
    editNamError.value = false
    editPasError.value = false
    alert('更新用户成功')
    // 修改成功，返回
    handleCloseEditBox()
  }
}

/* ----------button下线 用户提示、数据、列表渲染---------- */
/* 事件处理 下线用户函数 */
const handleOfflineUser = async (index) => {
  const offlineUser = allUserList.value[index]
  const result = confirm(
    `确定要下线<${
      offlineUser.type === 'admin'
        ? '管理员'
        : `${offlineUser.type === 'common' ? '普通用户' : '交通部门'}`
    }>: '${offlineUser.username}' 的用户账号吗？`
  )
  if (result) {
    offlineUser.isOnline = false
    const res = await getLogoutHttp(offlineUser)
    console.log(JSON.parse(res.config.data)) // 打印 下线的用户信息
    if (res.status === 200) {
      alert('操作成功，该用户已下线！')
    } else {
      alert('下线失败！')
    }
  }
}

onMounted(async () => {
  // 获取所有common用户信息
  let res = await getUsersHttp({
    type: 'common',
  })
  let manageCommonList = res.data.result
  // 获取所有traffic用户信息
  res = await getUsersHttp({
    type: 'traffic',
  })
  trafficUserList.value = res.data.result
  // 获取admin用户信息
  res = await getUsersHttp({
    type: 'admin',
  })
  let manageAdminList = res.data.result
  // 合并用户信息
  let twoUsers = trafficUserList.value.concat(manageCommonList)
  allUserList.value = manageAdminList.concat(twoUsers)
  // 存储 合并用户信息
  localStorage.setItem('allUserList', JSON.stringify(allUserList.value))
  let allUserListStr = localStorage.getItem('allUserList')
  if (allUserListStr) {
    allUserList.value = JSON.parse(allUserListStr)
  }
  console.log('超管所有用户列表:', allUserList.value)
})
</script>

<style scoped>
.userManage {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: absolute;
  top: 150px;
  left: 30%;
  /* transform: translate(-50%, -50%); */
  /* align-items: center; */
  width: 500px;
  /* height: 400px; */
  background-color: #fff;
  border-radius: 5px;
  padding: 15px;
  position: absolute; /* 确保浮动到顶部 */
  z-index: 1001; /* 确保在遮罩层之上 */
}
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明遮罩 */
  z-index: 1000; /* 确保在所有内容之上 */
}
.userAdd,
.userEdit {
  width: 450px;
  /* height: 300px; */
  position: absolute; /* 确保浮动到顶部 */
  top: 80px;
  left: 55%;
  /* transform: translate(-30%, -55%); */
  background-color: #fff;
  border-radius: 5px;
  border: 1px solid #ccc;
  padding: 15px;
  z-index: 1001; /* 确保在遮罩层和用户管理组件之上 */
}
.userAdd .addUserTitle,
.userEdit .editUserTitle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
}
.userAdd .addForm,
.userEdit .editForm {
  display: flex;
  flex-direction: column;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  color: #666;
  padding: 0 45px;
  margin: 10px 0;
}
.formItem1,
.formItem2 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 30px;
  margin-top: 10px;
}
.addErrorTip,
.editErrorTip {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-left: 15%;
  font-size: 12px;
  font-weight: 500;
  color: red;
}
.formItem1 input,
.formItem2 input {
  width: 85%;
  outline: none;
  border: 1px solid #ccc;
  padding: 5px;
  border-radius: 5px;
}
.userAdd .addBtn,
.userEdit .editBtn {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-top: 20px;
  margin: 10px 0;
  border-top: 1px solid #ccc;
}
.userAdd .addBtn button,
.userEdit .editBtn button {
  padding: 6px 12px;
  border: none;
  border-radius: 5px;
  background-color: #409eff;
  margin-left: 10px;
  color: #fff;
}
.userAdd .addBtn .cancelA,
.userEdit .editBtn .cancelE {
  border: 1px solid #ccc;
  background-color: #fff;
  color: #666;
}
.userAdd .addBtn .addA:hover {
  background-color: #66b1ff;
  cursor: pointer;
}
.userAdd .addBtn .cancelA:hover {
  background-color: #f2f2f2;
  cursor: pointer;
}
.userEdit .editBtn .editE:hover {
  background-color: #66b1ff;
  cursor: pointer;
}
.userEdit .editBtn .cancelE:hover {
  background-color: #f2f2f2;
  cursor: pointer;
}
.userManage .manageTitle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #ccc;
}
.close {
  font-weight: bold;
}
.close:hover {
  cursor: pointer;
  color: red;
}
.manageNav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.manageNav .navAdd {
  font-size: 14px;
  padding: 3px 6px;
  border-radius: 5px;
  border: 1px solid #ccc;
  cursor: pointer;
}
.manageNav .navEdit {
  display: flex;
  align-items: center;
}
.navEdit input {
  /* margin-right: 5px; */
  outline: none;
  border: 1px solid #ccc;
  padding: 5px;
  border-radius: 5px;
}
.navEdit div {
  height: 25px;
  width: 30px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 10px;
  cursor: pointer;
}
.icon-container i {
  color: black; /* 默认颜色 */
  transition: color 0.1; /* 添加平滑过渡效果 */
}
.navEdit div:hover.icon-container i {
  color: rgba(64, 158, 255, 0.5); /* 鼠标悬停时的颜色 */
  z-index: 100;
}
.manageUserList {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
}
.manageUserList table {
  width: 100%;
  border: 1px solid #ccc;
  border-collapse: collapse;
}
.manageUserList table th,
.manageUserList table td {
  border: 1px solid #ccc;
  text-align: center;
}
.manageUserList table th {
  color: #666;
  padding: 5px;
}
.manageUserList table td {
  padding: 3px;
}
.manageUserList table th {
  background-color: #f2f2f2;
}
.manageUserList table td {
  font-size: 14px;
}
.manageUserList table td:nth-child(5) {
  display: flex;
  justify-content: center;
  align-items: center;
}
.manageUserList table td:nth-child(5) button {
  margin-right: 5px;
  padding: 3px 8px;
  border: none;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
}
.manageUserList table td .edit {
  background-color: #409eff;
}
.manageUserList table td .delete {
  background-color: #d9534f;
}
.manageUserList table td .offline {
  background-color: #f0ad4e;
}
.manageUserList table td:nth-child(5) button:hover {
  color: black;
  opacity: 0.7;
}
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
